package cn.filter;

import cn.utils.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import javax.servlet.*;
import java.io.IOException;

public class OpenSessionInViewFilter implements Filter {
    public OpenSessionInViewFilter() {
        super();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,
        ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Transaction tx = null;
        try {
            tx = HibernateUtil.currentSession().beginTransaction();
            filterChain.doFilter(servletRequest,servletResponse);
            HibernateUtil.commit(tx);
        } catch (HibernateException e) {
            e.printStackTrace();
            HibernateUtil.rollback(tx);
        }
    }
}
